<template>
  <canvas  ref="panelCanvasBg" class="fabric-panel" :style="panelSty"></canvas>
</template>
<script>
import {fabric} from "fabric"
export default {
  data() {
    return {
      panelSty:{
        left:"",
        top:"",
      }
    }
  },
  methods: {
    setPosition(myChart){
      this.panelSty.left=myChart.getWidth()*0.1+'px'
      this.panelSty.top=myChart.getHeight()*0.1+'px'
    },
    setLayout(myChart,PanelForB6) {
      if(!myChart){
        return
      }
      this.setPosition(myChart)
      const gridComponent = myChart.getModel().getComponent('grid');
      const {width} = gridComponent.coordinateSystem.getRect();
      let {totalWidth, totalHeight, qpanelInfos} = PanelForB6
      let scale=width/totalWidth//画布数据和散点图内容区域比例
      this.wrapWidth = totalWidth* scale
      this.wrapHeight = totalHeight* scale
      let panelDom=this.$refs.panelCanvasBg
      const canvas = new fabric.StaticCanvas(panelDom, {
        width: this.wrapWidth, // 画布宽度
        height: this.wrapHeight, // 画布高度
        backgroundColor: 'white', // 画布背景色
      })
      canvas.renderOnAddRemove = false // 关闭自动
      let objectsToAdd = []
      for (let it of qpanelInfos) {
        for (let it2 of it.panelInfos) {
          objectsToAdd.push(this.setRectTxtGroup(it2, totalWidth, totalHeight))
        }
        objectsToAdd.push(this.setRectTxtGroup(it, totalWidth, totalHeight, true))
      }
      canvas.add(...objectsToAdd)
      canvas.setZoom(scale)
    },
    setRectTxtGroup(it, totalWidth, totalHeight, isQ = false) {//大Q降低不透明度，扩大字体100px
      let {topLeftX, topLeftY, bottomRightX, bottomRightY, panelId} = it
      let width = Math.abs(bottomRightX - topLeftX)
      let height = Math.abs(bottomRightY - topLeftY)

      // 1. 限制字体大小的逻辑
      const minDim = Math.min(width, height);
      let calculatedFontSize =  minDim * 0.5;//为Q时，缩放0.8倍，为panel时，缩小一半
      let scaleList=[{len:3,scale:0.8},{len:4,scale:0.7},{len:5,scale:0.6},{len:6,scale:0.5},{len:7,scale:0.4},{len:8,scale:0.3},{len:9,scale:0.3},{len:10,scale:0.3}]
      if(panelId.length>2){
        let scaleItem=scaleList.find(item=>item.len===panelId.length)
        calculatedFontSize=calculatedFontSize*scaleItem.scale
      }
      let rect = new fabric.Rect({
        width,
        height,
        fill: 'white',
        stroke: isQ ? 'red' : 'black',        // 边框颜色
        strokeWidth: 1,
        originX: 'center',
        originY: 'center',
      })
      const text = new fabric.Text(panelId, {
        fontSize: calculatedFontSize,
        fill: '#000',
        originX: 'center',
        originY: 'center',
      })

      return new fabric.Group([rect, text], {
        left: totalWidth / 2 + topLeftX,
        top: totalHeight / 2 - topLeftY,
        originX: 'left',
        originY: 'top',
        opacity: isQ ? 0.2 : 1,
      })
    },
  },
}
</script>
<style  lang="stylus">
.fabric-panel{
  position absolute;
  border 1px solid red;
}
</style>